package com.anis.project.medcare.editors;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.Collator;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;
import javax.swing.JRootPane;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ExpandBar;
import org.eclipse.swt.widgets.ExpandItem;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.wb.swt.SWTResourceManager;

import com.anis.jpa.medical.model.Common;
import com.anis.jpa.medical.model.MedicalReport;
import com.anis.jpa.medical.model.Patient;
import com.anis.project.medcare.Activator;
import com.anis.project.medcare.dicom.viewer.view.SWTImageCanvas;
import com.anis.project.medcare.editors.input.PatientEditorInput;
import com.anis.project.medcare.editors.table.content.providers.ReportTableContentProvider;
import com.anis.project.medcare.editors.table.content.providers.ReportTableLabelProvider;
import com.anis.project.medcare.ooswriter.OOoSwtViewer;
import com.anis.project.medcare.search.dialog.NewAppointementDialog;

/**
 * An example showing how to create a multi-page editor. This example has 3
 * pages:
 * <ul>
 * <li>page 0 contains a nested text editor.
 * <li>page 1 allows you to change the font used in page 2
 * <li>page 2 shows the words in page 0 in sorted order
 * </ul>
 */
public class PatientEditor extends MultiPageEditorPart {

	/** The font chosen in page 1. */
	private Font font;

	public static final String ID = "com.anis.project.medcare.editors.patient";

	private static final String MEDICAL_REPORT = "Medical Report";

	private static final String RADIO_REPORT = "Radio Report";

	private Text nameText;
	private Text lastNameText;
	private Text patientIDText;
	private Text addressText;
	private Text phoneText;
	private boolean m_isDirtyFlag = false;
	protected String title;
	protected String patientName;
	protected String lastName;
	protected String patientAddress;
	protected Integer patientPhone;
	protected String patientGender;
	protected String patienID;
	private Text text;
	private OOoSwtViewer viewer;
	private Integer cnamID;
	private Patient patient;
	private PatientEditorInput patientEditorInput;
	private Text creationDateText;
	private Date creationDate;
	private Combo comboTitle;
	private Combo genderCombo;
	private Date patientBirthDay;
	private DateTime birthday;
	private Text numMatricule;
	private Combo typeCombo;
	private DateTime validityDate;
	private String cnamType;
	private Date cnamValDate;
	private Text usfullNotesText;
	protected String usfullNotes;
	private Text appointementText;
	private Label patientImageLabel;
	private Table listOfPatientReports;
	private String nextRdv;

	/**
	 * Creates a multi-page editor example.
	 */
	public PatientEditor() {
		super();

	}

	/**
	 * Creates page 0 of the multi-page editor, which contains a text editor.
	 */
	void createPage0() {
		CTabItem parentContainer = new CTabItem((CTabFolder) getContainer(),
				SWT.NONE);
		// Composite parent = new Composite(getContainer(), SWT.NONE);
		Form container = new Form(getContainer(), SWT.NONE);
		parentContainer.setText("Patient Information");
		parentContainer.setControl(container);
		container.getBody().setLayout(new GridLayout(7, false));

		patientImageLabel = new Label(container.getBody(), SWT.BORDER
				| SWT.CENTER);
		GridData gd_patientImageCancas = new GridData(SWT.FILL, SWT.FILL,
				false, false, 2, 1);
		gd_patientImageCancas.heightHint = 167;
		gd_patientImageCancas.widthHint = 136;
		patientImageLabel.setLayoutData(gd_patientImageCancas);

		patientImageLabel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
			}
		});

		ExpandBar expandBar = new ExpandBar(container.getBody(), SWT.BORDER);
		expandBar.setTouchEnabled(true);
		expandBar.setForeground(SWTResourceManager
				.getColor(SWT.COLOR_WIDGET_FOREGROUND));
		GridData gd_expandBar = new GridData(SWT.FILL, SWT.FILL, true, true, 5,
				8);
		gd_expandBar.widthHint = 372;
		gd_expandBar.heightHint = 125;
		expandBar.setLayoutData(gd_expandBar);

		ExpandItem xpndtmNewExpanditem = new ExpandItem(expandBar, SWT.NONE);
		xpndtmNewExpanditem.setText("General Properties");

		Composite composite = new Composite(expandBar, SWT.NONE);
		xpndtmNewExpanditem.setControl(composite);
		composite.setLayout(new GridLayout(2, false));

		Label lblName = new Label(composite, SWT.NONE);
		lblName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1,
				1));
		lblName.setText("Name :");

		nameText = new Text(composite, SWT.BORDER);
		GridData gd_nameText = new GridData(SWT.LEFT, SWT.FILL, true, false, 1,
				1);
		gd_nameText.widthHint = 132;
		nameText.setLayoutData(gd_nameText);
		nameText.setSize(74, 21);
		nameText.setText(patientEditorInput.getPatientName());

		nameText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!nameText.getText().equals(patientEditorInput.getName()))
					setDirtyFlag(true);
				else
					setDirtyFlag(false);
				patientName = nameText.getText();
			}
		});

		Label lblStatus = new Label(composite, SWT.NONE);
		lblStatus.setText("Title :");

		comboTitle = new Combo(composite, SWT.NONE);
		GridData gd_comboTitle = new GridData(SWT.LEFT, SWT.FILL, true, false,
				1, 1);
		gd_comboTitle.widthHint = 132;
		comboTitle.setLayoutData(gd_comboTitle);

		comboTitle.add("Mr.");
		comboTitle.add("Ms.");
		comboTitle.add("Mlle.");
		comboTitle.setText(patientEditorInput.getPatientTitle());
		comboTitle.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!comboTitle.isDisposed() && comboTitle.getText() != null) {
					setDirtyFlag(!comboTitle.getText().equals(
							patientEditorInput.getPatientTitle()));
				}
				title = comboTitle.getText();
			}
		});

		Label lblLastName = new Label(composite, SWT.NONE);
		lblLastName.setText("Last Name :");

		lastNameText = new Text(composite, SWT.BORDER);
		GridData gd_lastNameText = new GridData(SWT.LEFT, SWT.FILL, true,
				false, 1, 1);
		gd_lastNameText.widthHint = 132;
		lastNameText.setLayoutData(gd_lastNameText);
		lastNameText.setText(patientEditorInput.getPatientLastName());

		lastNameText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!lastNameText.getText().equals(
						patientEditorInput.getPatientLastName()))
					setDirtyFlag(true);
				else
					setDirtyFlag(false);
				lastName = lastNameText.getText();
			}
		});

		Label lblAddress = new Label(composite, SWT.NONE);
		lblAddress.setText("Address :");

		addressText = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.MULTI);
		GridData gd_addressText = new GridData(SWT.LEFT, SWT.FILL, true, false,
				1, 1);
		gd_addressText.widthHint = 132;
		addressText.setLayoutData(gd_addressText);
		addressText.setTouchEnabled(true);
		addressText.setText(patientEditorInput.getPatientAddress());

		addressText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!addressText.getText().equals(
						patientEditorInput.getPatientAddress()))
					setDirtyFlag(true);
				else
					setDirtyFlag(false);
				patientAddress = addressText.getText();
			}
		});

		Label lblPhone = new Label(composite, SWT.NONE);
		lblPhone.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false,
				1, 1));
		lblPhone.setText("Phone :");

		phoneText = new Text(composite, SWT.BORDER);
		GridData gd_phoneText = new GridData(SWT.LEFT, SWT.FILL, true, false,
				1, 1);
		gd_phoneText.widthHint = 132;
		phoneText.setLayoutData(gd_phoneText);
		phoneText.setText(patientEditorInput.getPatientPhone());

		phoneText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!phoneText.getText().equals(
						patientEditorInput.getPatientPhone())) {
					setDirtyFlag(true);
				} else
					setDirtyFlag(false);
				if (!phoneText.getText().isEmpty())
					patientPhone = Integer.valueOf(phoneText.getText());
			}
		});
		xpndtmNewExpanditem.setHeight(150);

		ExpandItem xpndtmNewExpanditem_1 = new ExpandItem(expandBar, SWT.NONE);
		xpndtmNewExpanditem_1.setText("CNAM");

		Composite composite_1 = new Composite(expandBar, SWT.NONE);
		xpndtmNewExpanditem_1.setControl(composite_1);
		xpndtmNewExpanditem_1.setHeight(150);
		composite_1.setLayout(new GridLayout(2, false));

		Label lblGender = new Label(composite_1, SWT.NONE);
		lblGender.setText("Gender :");

		genderCombo = new Combo(composite_1, SWT.NONE);
		genderCombo.add("Male");
		genderCombo.add("Female");
		genderCombo.setText(patientEditorInput.getPatientGender());

		Label lbBirthday = new Label(composite_1, SWT.NONE);
		lbBirthday.setText("Birthday :");

		birthday = new DateTime(composite_1, SWT.BORDER);
		birthday.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		Label lbMatricule = new Label(composite_1, SWT.NONE);
		lbMatricule.setText("CNAM ID :");

		numMatricule = new Text(composite_1, SWT.BORDER);
		numMatricule.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		Label lblType = new Label(composite_1, SWT.NONE);
		lblType.setText("Type :");

		typeCombo = new Combo(composite_1, SWT.NONE);
		typeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		typeCombo.add("CNSS");
		typeCombo.add("CNRPS");
		Label lblPatientId_1 = new Label(composite_1, SWT.NONE);
		lblPatientId_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		lblPatientId_1.setText("Validity Date :");

		validityDate = new DateTime(composite_1, SWT.BORDER);
		validityDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));

		ExpandItem xpndtmNewExpanditem_2 = new ExpandItem(expandBar, SWT.NONE);
		xpndtmNewExpanditem_2.setExpanded(true);
		xpndtmNewExpanditem_2.setText("Personal Notes");

		Composite furtherInformation = new Composite(expandBar, SWT.NONE);
		xpndtmNewExpanditem_2.setControl(furtherInformation);
		furtherInformation.setLayout(new GridLayout(1, false));

		usfullNotesText = new Text(furtherInformation, SWT.BORDER | SWT.WRAP
				| SWT.V_SCROLL | SWT.MULTI);
		usfullNotesText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		usfullNotesText.setBackground(SWTResourceManager
				.getColor(255, 255, 204));

		usfullNotesText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!usfullNotesText.getText().equals(
						patientEditorInput.getPatientUsefullNotes()))
					setDirtyFlag(true);
				else
					setDirtyFlag(false);
				usfullNotes = usfullNotesText.getText();
			}
		});
		xpndtmNewExpanditem_2.setHeight(150);

		validityDate.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				int day = validityDate.getDay();
				int month = validityDate.getMonth() + 1;
				int year = validityDate.getYear();

				String valDate = String.valueOf(year) + "-"
						+ String.valueOf(month) + "-" + String.valueOf(day);
				DateFormat dateFormat = new SimpleDateFormat(Common.DATE_FORMAT);

				try {
					Date date = dateFormat.parse(valDate);
					try {
						if (!patient.getCnamValidityDate().equals(date)) {
							setDirtyFlag(true);
							cnamValDate = date;
						} else
							setDirtyFlag(false);
					} catch (NullPointerException e2) {
						cnamValDate = date;
					}
					setDirtyFlag(true);
				} catch (ParseException e1) {

				}
			}
		});

		typeCombo.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!typeCombo.getText().equals(
						patientEditorInput.getPatientCnamType()))
					setDirtyFlag(true);
				else
					setDirtyFlag(false);
				if (!numMatricule.getText().isEmpty())
					cnamType = typeCombo.getText();
				else
					cnamType = typeCombo.getSelection().toString();
			}
		});

		numMatricule.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!numMatricule.getText().equals(
						patientEditorInput.getPatientCnamID()))
					setDirtyFlag(true);
				else
					setDirtyFlag(false);
				if (!numMatricule.getText().isEmpty()) {
					try {
						cnamID = Integer.valueOf(numMatricule.getText());
					} catch (NumberFormatException e2) {
						// TODO: handle exception
					}

				}

				else
					cnamID = 0;

			}
		});

		birthday.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				int day = birthday.getDay();
				int month = birthday.getMonth() + 1;
				int year = birthday.getYear();

				String birthfayDay = String.valueOf(year) + "-"
						+ String.valueOf(month) + "-" + String.valueOf(day);
				DateFormat dateFormat = new SimpleDateFormat(Common.DATE_FORMAT);

				try {
					Date date = dateFormat.parse(birthfayDay);
					try {
						if (patient.getBirthDay() != date) {
							setDirtyFlag(true);
							patientBirthDay = date;
						} else
							setDirtyFlag(false);
					} catch (NullPointerException e2) {
						patientBirthDay = date;
					}
					setDirtyFlag(true);
				} catch (ParseException e1) {

				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub

			}
		});

		genderCombo.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!genderCombo.isDisposed() && genderCombo.getText() != null) {
					setDirtyFlag(!genderCombo.getText().equals(
							patientEditorInput.getPatientGender()));
				} else
					setDirtyFlag(false);
				patientGender = genderCombo.getText();
			}
		});
		DateFormat dateFormat = new SimpleDateFormat(Common.DATE_FORMAT);
		creationDate = new Date();
		if (patient != null) {
			if (patient.getPatientimage().equals(null)) {
				patientImageLabel.setImage(Activator.getDefault().getImage(
						"noimage"));
			} else {
				byte[] imageInByt = patient.getPatientimage();
				BufferedInputStream inputStreamReader = new BufferedInputStream(
						new ByteArrayInputStream(imageInByt));
				ImageData imageData = new ImageData(inputStreamReader);
				Image patientImage = new Image(null, imageData);
				patientImageLabel.setImage(patientImage);
			}
		} else
			patientImageLabel.setImage(Activator.getDefault().getImage(
					"noimage"));

		Button lbFoto = new Button(container.getBody(), SWT.NONE);
		lbFoto.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});
		lbFoto.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				2, 1));
		lbFoto.setText("Take a Foto");

		Label lblCreationDate = new Label(container.getBody(), SWT.NONE);
		lblCreationDate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		lblCreationDate.setSize(78, 21);
		lblCreationDate.setText("Creation Date :");

		creationDateText = new Text(container.getBody(), SWT.BORDER
				| SWT.READ_ONLY);
		creationDateText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				false, false, 1, 1));
		creationDateText.setSize(156, 21);
		creationDateText.setText(dateFormat.format(creationDate));
		Label lblPatientId = new Label(container.getBody(), SWT.NONE);
		lblPatientId.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		lblPatientId.setSize(453, 15);
		lblPatientId.setText("Patient ID :");

		patientIDText = new Text(container.getBody(), SWT.BORDER);
		patientIDText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		patientIDText.setSize(156, 21);
		patientIDText.setEnabled(false);
		patientIDText.setEditable(false);

		Label lblNextAppointementWith = new Label(container.getBody(), SWT.NONE);
		lblNextAppointementWith.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
				false, false, 1, 1));
		lblNextAppointementWith.setText("Next Appointement :");

		appointementText = new Text(container.getBody(), SWT.BORDER);
		appointementText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false,
				false, 1, 1));
		appointementText.setEnabled(false);
		appointementText.setEditable(false);
		appointementText.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				if (!appointementText.getText().equals(
						patientEditorInput.getPatientNextAppointement())
						&& !appointementText.getText().equals("0000-00-00")) {
					setDirty(true);
					nextRdv = appointementText.getText();
				}
			}
		});
//		Button newRdvButton = new Button(container.getBody(), SWT.NONE);
//		newRdvButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
//				false, 1, 1));
//		newRdvButton.addSelectionListener(new SelectionAdapter() {
//			@Override
//			public void widgetSelected(SelectionEvent e) {
//				Shell parentShell = Activator.getDefault().getWorkbench()
//						.getActiveWorkbenchWindow().getShell();
//				NewAppointementDialog newAppointmentDialog = new NewAppointementDialog(
//						parentShell, appointementText);
//				newAppointmentDialog.open();
//			}
//		});
//
//		newRdvButton.setText("New Appointement");
		new Label(container.getBody(), SWT.NONE);
		new Label(container.getBody(), SWT.NONE);
		new Label(container.getBody(), SWT.NONE);
		new Label(container.getBody(), SWT.NONE);
		new Label(container.getBody(), SWT.NONE);

		if (patientEditorInput.getPatientID() != null)
			patientIDText.setText(patientEditorInput.getPatientID());
		else
			patientIDText.setText("Patient not yet saved in database");
		if (patientEditorInput.getPatientBirthDay() != null) {
			Date date = patientEditorInput.getPatientBirthDay();
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH);
			int day = cal.get(Calendar.DAY_OF_MONTH);
			birthday.setDate(year, month, day);
		}
		if (patientEditorInput.getPatientNextAppointement() != null)
			appointementText.setText(patientEditorInput
					.getPatientNextAppointement());
		if (patientEditorInput.getPatientNextAppointement() != null) {
			appointementText.setText(patientEditorInput
					.getPatientNextAppointement().toString());
		} else {
			appointementText.setText("0000-00-00");
		}
		if (patientEditorInput.getPatientCnamID() != null)
			numMatricule.setText(String.valueOf(patientEditorInput
					.getPatientCnamID()));
		if (patientEditorInput.getPatientCnamType() != null)
			typeCombo.setText(patientEditorInput.getPatientCnamType());

		if (patientEditorInput.getPatientCnamValidityDate() != null) {
			Date date = patientEditorInput.getPatientCnamValidityDate();
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH);
			int day = cal.get(Calendar.DAY_OF_MONTH);
			validityDate.setDate(year, month, day);
		}
		if (patientEditorInput.getPatientUsefullNotes() != null)
			usfullNotesText
					.setText(patientEditorInput.getPatientUsefullNotes());

	}

	/**
	 * Creates page 1 of the multi-page editor, which allows you to change the
	 * font used in page 2.
	 */
	void createPage1() {
		CTabItem parentContainer = new CTabItem((CTabFolder) getContainer(),
				SWT.NONE);

		final Composite parent = new Composite(getContainer(), SWT.NONE);
		parentContainer.setText("Patient Reports");
		parentContainer.setControl(parent);

		Composite container = new Composite((CTabFolder) getContainer(),
				SWT.NONE);
		parentContainer.setControl(container);
		container.setLayout(new GridLayout(2, false));

		Group patientReports = new Group(container, SWT.NONE);
		patientReports.setText("Patient Reports");
		patientReports.setLayout(new GridLayout(1, false));
		GridData gridData = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
		gridData.widthHint = 270;
		patientReports.setLayoutData(gridData);

		Composite reportsContainer = new Composite(patientReports, SWT.NONE);
		reportsContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		TableColumnLayout tcl_reportsContainer = new TableColumnLayout();
		reportsContainer.setLayout(tcl_reportsContainer);

		TableViewer tableViewer = new TableViewer(reportsContainer, SWT.BORDER
				| SWT.FULL_SELECTION);
		listOfPatientReports = tableViewer.getTable();
		listOfPatientReports.setHeaderVisible(true);
		listOfPatientReports.setLinesVisible(true);

		TableViewerColumn tableViewerColumn = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn reportNameColumn = tableViewerColumn.getColumn();
		tcl_reportsContainer.setColumnData(reportNameColumn,
				new ColumnPixelData(76, true, true));
		reportNameColumn.setText("Report Name");

		TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn reportDescriptionColumn = tableViewerColumn_1.getColumn();
		tcl_reportsContainer.setColumnData(reportDescriptionColumn,
				new ColumnPixelData(93, true, true));
		reportDescriptionColumn.setText("Report Description");

		TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnNewColumn = tableViewerColumn_2.getColumn();
		tcl_reportsContainer.setColumnData(tblclmnNewColumn,
				new ColumnPixelData(115, true, true));
		tblclmnNewColumn.setText("Report Type");

		tableViewer.setContentProvider(new ReportTableContentProvider());
		tableViewer.setLabelProvider(new ReportTableLabelProvider());
		tableViewer.setInput(this.patientEditorInput.getReportList());

		final Group reportsViewer = new Group(container, SWT.NO_BACKGROUND
				| SWT.EMBEDDED);
		reportsViewer.setText("Reports Viewer");
		reportsViewer.setLayout(new GridLayout(1, false));
		reportsViewer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				false, 1, 1));

		tableViewer.addDoubleClickListener(new IDoubleClickListener() {

			@Override
			public void doubleClick(DoubleClickEvent event) {
				final StructuredSelection selection = (StructuredSelection) event
						.getSelection();
				try {
					PlatformUI.getWorkbench().getProgressService()
							.busyCursorWhile(new IRunnableWithProgress() {

								@Override
								public void run(final IProgressMonitor monitor)
										throws InvocationTargetException,
										InterruptedException {

									if (selection.getFirstElement() instanceof MedicalReport) {
										String reportType = ((MedicalReport) selection
												.getFirstElement())
												.getReportType();
										if (reportType != null
												&& reportType
														.equals(Common.MEDREPTYPE)) {
											Display.getDefault().asyncExec(
													new Runnable() {

														@Override
														public void run() {
															openMedicalReport(
																	reportsViewer,
																	(MedicalReport) selection
																			.getFirstElement(),
																	monitor);

														}
													});

										} else if (reportType != null
												&& reportType
														.equals(Common.RADREPTYPE)) {
											openRadioReport(reportsViewer,
													(MedicalReport) selection
															.getFirstElement());
										} else {
											MessageDialog.openError(
													parent.getShell(),
													"Unkown Type",
													"The Report type is unsupported !");
										}
									}

								}
							});
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
	}

	/**
	 * Creates the pages of the multi-page editor.
	 */
	protected void createPages() {
		createPage0();
		createPage1();
	}

	/**
	 * The <code>MultiPageEditorPart</code> implementation of this
	 * <code>IWorkbenchPart</code> method disposes all nested editors.
	 * Subclasses may extend.
	 */
	public void dispose() {
		super.dispose();
	}

	/**
	 * Saves the multi-page editor's document.
	 */
	public void doSave(IProgressMonitor monitor) {
		// getEditor(0).doSave(monitor);
		patient = patientEditorInput.getPatient();
		ArrayList<MedicalReport> listOfRadioReports = new ArrayList<>();
		if (patient == null) {
			patient = new Patient(patientName, lastName, patientPhone,
					patientBirthDay, creationDate, title, patientGender,
					patientAddress, listOfRadioReports);

		} else {
			if (patientAddress != null)
				patient.setPatientaddress(patientAddress);
			if (lastName != null)
				patient.setPatientlastname(lastName);
			if (patientName != null)
				patient.setPatientname(patientName);
			if (patientGender != null)
				patient.setPatientsex(patientGender);
			if (title != null)
				patient.setPatienttitle(title);
			if (patientBirthDay != null)
				patient.setPatientBirthday(patientBirthDay);
			if (creationDate != null)
				patient.setPatientCreationdate(creationDate);
			if (patientPhone != null)
				patient.setPhone(patientPhone);
			if (cnamID != null)
				patient.setCnamID(cnamID);
			if (cnamType != null)
				patient.setCnamType(cnamType);
			if (cnamValDate != null)
				patient.setCnamValidityDate(cnamValDate);
			if (usfullNotes != null)
				patient.setpatientUseFullNotes(usfullNotes);
			if (patientImageLabel.getImage() != null) {
				patient.setPatientimage(getImgBytes(patientImageLabel
						.getImage()));
			}
			if (nextRdv != null)
				patient.setrdvDate(nextRdv);

		}
		setPartName(patient.getPatientname());
		String id = Activator.getDefault().databaseBinder()
				.savePatient(patient);
		patientIDText.setText(id);
		setDirtyFlag(false);
	}

	/**
	 * Saves the multi-page editor's document as another file. Also updates the
	 * text for page 0's tab, and updates this multi-page editor's input to
	 * correspond to the nested editor's.
	 */
	public void doSaveAs() {
		IEditorPart editor = getEditor(0);
		editor.doSaveAs();
		setPageText(0, editor.getTitle());
		setInput(editor.getEditorInput());
	}

	/**
	 * The <code>MultiPageEditorExample</code> implementation of this method
	 * checks that the input is an instance of <code>IFileEditorInput</code>.
	 */
	public void init(IEditorSite site, IEditorInput editorInput)
			throws PartInitException {
		if (!(editorInput instanceof PatientEditorInput))
			throw new PartInitException(
					"Invalid Input: Must be PatientEditorInput");

		this.patientEditorInput = (PatientEditorInput) editorInput;
		super.init(site, patientEditorInput);
	}

	/*
	 * (non-Javadoc) Method declared on IEditorPart.
	 */
	public boolean isSaveAsAllowed() {
		return true;
	}

	/**
	 * Calculates the contents of page 2 when the it is activated.
	 */
	protected void pageChange(int newPageIndex) {
		super.pageChange(newPageIndex);
		if (newPageIndex == 2) {
			sortWords();
		}
	}

	/**
	 * Sets the font related data to be applied to the text in page 2.
	 */
	void setFont() {
		FontDialog fontDialog = new FontDialog(getSite().getShell());
		fontDialog.setFontList(text.getFont().getFontData());
		FontData fontData = fontDialog.open();
		if (fontData != null) {
			if (font != null)
				font.dispose();
			font = new Font(text.getDisplay(), fontData);
			text.setFont(font);
		}
	}

	/**
	 * Sorts the words in page 0, and shows them in page 2.
	 */
	void sortWords() {

		String editorText = "test";

		StringTokenizer tokenizer = new StringTokenizer(editorText,
				" \t\n\r\f!@#\u0024%^&*()-_=+`~[]{};:'\",.<>/?|\\");
		ArrayList editorWords = new ArrayList();
		while (tokenizer.hasMoreTokens()) {
			editorWords.add(tokenizer.nextToken());
		}

		Collections.sort(editorWords, Collator.getInstance());
		StringWriter displayText = new StringWriter();
		for (int i = 0; i < editorWords.size(); i++) {
			displayText.write(((String) editorWords.get(i)));
			displayText.write(System.getProperty("line.separator"));
		}
		text.setText(displayText.toString());
	}

	public void setDirty(boolean flag) {
		setDirtyFlag(flag);
	}

	@Override
	public boolean isDirty() {
		return m_isDirtyFlag;
	}

	private void setDirtyFlag(boolean flag) {
		m_isDirtyFlag = flag;
		firePropertyChange(MultiPageEditorPart.PROP_DIRTY);
	}

	private byte[] getImgBytes(Image image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			ImageIO.write(getBufferedImage(image), "JPEG", baos);
		} catch (IOException ex) {
			// handle it here.... not implemented yet...
		}
		return baos.toByteArray();
	}

	private BufferedImage getBufferedImage(Image image) {
		int width = image.getImageData().width;
		int height = image.getImageData().height;
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		return bi;
	}

	private void openRadioReport(Group parentGRoup, MedicalReport medicalReport) {

		final SWTImageCanvas swtImageCanvas = new SWTImageCanvas(parentGRoup,
				SWT.FILL);
		swtImageCanvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));

		Group group = new Group(parentGRoup, SWT.NONE);
		group.setLayout(new GridLayout(1, false));
		group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));

		final Slider slider = new Slider(group, SWT.NONE);
		final ArrayList<ImageData> dicomList = byteArrayToWrapperList(medicalReport
				.getReportcontent());
		slider.setMinimum(0);
		slider.setIncrement(1);
		slider.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				swtImageCanvas.loadImage((ImageData) dicomList.get(slider
						.getSelection()));
				slider.setToolTipText("Slide Number :" + slider.getSelection());
			}
		});
		slider.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		Point size = parentGRoup.getSize();
		parentGRoup.setSize(0, 0);
		parentGRoup.setSize(size);
		parentGRoup.redraw();

	}

	private void openMedicalReport(Group parentGRoup, MedicalReport selection,
			IProgressMonitor monitor) {
		try {
			System.setProperty("sun.awt.noerasebackground", "true");
		} catch (NoSuchMethodError error) {
		}
		monitor.beginTask("Frame creation...", 100);
		/* Create and setting up frame */
		Frame frame = SWT_AWT.new_Frame(parentGRoup);
		Panel panel = new Panel(new BorderLayout()) {
			public void update(java.awt.Graphics g) {
				paint(g);
			}
		};
		monitor.worked(30 / 100);
		frame.add(panel);
		JRootPane root = new JRootPane();
		panel.add(root);
		java.awt.Container contentPane = root.getContentPane();
		viewer = new OOoSwtViewer();
		contentPane.add(viewer);
		monitor.worked(40 / 100);
		monitor.beginTask("Retrieving binary from database...", 100);
		monitor.worked(70 / 100);
		try {
			byte[] radioReportContent = selection.getReportcontent();
			monitor.worked(70 / 100);
			if (null != radioReportContent)
				viewer.setDocumentBinary(radioReportContent);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		monitor.worked(100 / 100);
		parentGRoup.setText(selection.getReportName());
		Point size = parentGRoup.getSize();
		parentGRoup.setSize(0, 0);
		parentGRoup.setSize(size);
		parentGRoup.redraw();

	}

	public ArrayList<ImageData> byteArrayToWrapperList(byte[] byteArray) {
		ArrayList<ImageData> list = new ArrayList<ImageData>();
		ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
		for (int i = 0; i < byteArray.length; i++) {
			ImageData img = new ImageData(bis);
			list.add(img);
		}
		return list;
	}

}
